package cn.stronglink.assetmanage.business.check.view.wait;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import cn.stronglink.assetmanage.MainActivity;
import cn.stronglink.assetmanage.R;
import cn.stronglink.assetmanage.business.check.adapter.CheckOrderAdapter;
import cn.stronglink.assetmanage.business.check.model.WaitAssetModel;
import cn.stronglink.assetmanage.business.check.presenter.WaitAssetPresenter;
import cn.stronglink.assetmanage.business.check.view.detail.AddCheckDetailFragment;
import cn.stronglink.assetmanage.business.check.view.detail.WaitCheckDetailFragment;
import cn.stronglink.assetmanage.business.search.view.AssisChange.AssisChangeFragment;
import cn.stronglink.assetmanage.business.task.model.ITaskSyncListener;
import cn.stronglink.assetmanage.business.task.model.OrderType;
import cn.stronglink.assetmanage.business.task.model.TaskSyncModel;
import cn.stronglink.assetmanage.entity.Asset;
import cn.stronglink.assetmanage.entity.Check;
import cn.stronglink.assetmanage.entity.User;
import cn.stronglink.assetmanage.index.base.BaseChildFragment;
import cn.stronglink.assetmanage.index.entity.PromissionEntity;
import cn.stronglink.assetmanage.index.view.onRecyclerListener;
import cn.stronglink.assetmanage.utils.Constants;
import cn.stronglink.assetmanage.utils.ToastUtil;

/**
 * 待入库资产列表
 */
public class WaitAssetFragment extends BaseChildFragment implements View.OnClickListener, ITaskSyncListener {
    protected Activity mActivity;
    RecyclerView rv_checkwait_list;
    String orderNo;
    private WaitAssetView waitAssetView;
    //资源列表adapter
    private CheckOrderAdapter orderAdapter;
    private WaitAssetModel waitAssetModel;
    private LinearLayoutManager layoutManager;
    private Button btn_change_check_status;
    private Button butSaveOrder;
    private Check check;
    private List<Asset> assetList = null;
    private TextView txt_title_right, txt_title_left, txt_main_title;
    private TaskSyncModel taskSyncModel;
    private List<Asset> orderList;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mActivity = (Activity) context;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_wait_asset, container, false);
        initViewAndData(view);
        return view;
    }

    private void initViewAndData(View view) {
        try {
            txt_title_right = this.getActivity().findViewById(R.id.txt_right_title);
            txt_title_right.setVisibility(View.INVISIBLE);
            txt_title_left = this.getActivity().findViewById(R.id.txt_left_title);
            txt_title_left.setVisibility(View.VISIBLE);
            txt_main_title = this.getActivity().findViewById(R.id.txt_main_title);
            txt_main_title.setText("待入库");
            assetList = new ArrayList<>();
            rv_checkwait_list = view.findViewById(R.id.rv_checkwait_list);
            orderAdapter = new CheckOrderAdapter(getActivity());
            layoutManager = new LinearLayoutManager(this.getActivity(), LinearLayout.VERTICAL, false);
            rv_checkwait_list.setLayoutManager(layoutManager);
            rv_checkwait_list.setAdapter(orderAdapter);
            rv_checkwait_list.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
            txt_title_left.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mActivity.onBackPressed();
                }
            });
            txt_title_right.setOnClickListener(this);
            orderAdapter.setOnItemClickListener(new onRecyclerListener() {
                @Override
                public void onItemClicked(View v, int postion) {
                    //跳转页面
                    if (orderList != null && assetList.size() > 0) {
                        Asset asset = orderList.get(postion);
                        if (asset != null) {
                            MainActivity activity = (MainActivity) getActivity();
                            PromissionEntity pe = new PromissionEntity();
                            pe.setFragment(new WaitCheckDetailFragment());
                            pe.setPosition(MainActivity.FRAGMENT_CUSTOM_ID);
                            pe.setTitle("资产详情");
                            // 设置打开盘点详情后传递的参数
                            Bundle bundle = new Bundle();
                            bundle.putSerializable(Constants.CHECK_IN_DETAIL_NO, asset.getAsset_id_key());
                            pe.setBundle(bundle);
                            activity.onEventRegister(pe);
                        }
                    }
                }
            });
            waitAssetView = new WaitAssetView(this, view, orderAdapter);
            waitAssetModel = new WaitAssetModel();
            taskSyncModel = new TaskSyncModel();
            taskSyncModel.setListener(this);
            Bundle bundle = getArguments();
            if (bundle != null) {
                orderNo = bundle.getString(Constants.CHECK_IN_DETAIL_NO);
                if (orderNo != null && !"".equals(orderNo)) {
                    //需要根据任务fragment传递过来的表单号显示资产列表
                    orderList = waitAssetModel.getDataByOrderNo(orderNo);
                    waitAssetView.setOrderData(orderList);
                    waitAssetView.showAssetTitle(waitAssetModel.getCheckByOrderNo(orderNo));
                    check = waitAssetModel.getCheckByOrderNo(orderNo);
                    assetList = waitAssetModel.getDataByOrderNo(orderNo);
                    orderAdapter.notifyDatasChanged(assetList);
                }
            }
            btn_change_check_status = view.findViewById(R.id.btn_change_check_status);
            btn_change_check_status.setOnClickListener(this);

            butSaveOrder = view.findViewById(R.id.btn_save_order);
            butSaveOrder.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //判断是否自动同步数据
                    try {
                        judgeIsSyncData();
                    } catch (Exception e) {
                        e.printStackTrace();
                        ToastUtil.toastShort("没有数据显示");
                    }
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.toastShort("没有数据显示");
        }
    }

    private void judgeIsSyncData() {

        //表单中有sn和资产编号为空的不能修改为入库状态
        boolean hasNoWaitAsset = false;
        if (assetList != null && assetList.size() > 0) {
            for (int i = 0; i < assetList.size(); i++) {
                if (assetList.get(i).getSerialNo() == null || assetList.get(i).getAssetNo() == null) {
                    hasNoWaitAsset = true;
                    break;
                }
            }
            if (hasNoWaitAsset) {
                //有未入库的资产，则提示
                ToastUtil.toastShort("本单号中存在未入库资产，请将资产入库");
            } else {
                //将单子改为已经入库状态
                String time = new SimpleDateFormat("yyyy-MM-dd hh:MM:ss").format(new Date());
//                check.setUpdateTime(time);
//                check.setUpdateBy(Long.valueOf(User.getInstance().getId_()));
                waitAssetModel.saveCheckByButton(check);
                ToastUtil.toastShort("保存成功");
                mActivity.onBackPressed();
            }
        } else {
            ToastUtil.toastShort("本单为空单，不能入库");
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onResume() {
        super.onResume();
        getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        getView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int keycode, KeyEvent keyEvent) {
                if (keycode == KeyEvent.KEYCODE_BACK) {
                    mActivity.onBackPressed();
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    public void onFail(String orderNo, OrderType orderType, Exception e, int sum) {
        ToastUtil.toastShort("同步失败");
    }

    @Override
    public void onSucces(String orderNo, OrderType orderType, int sum) {
        ToastUtil.toastShort("同步成功");
    }    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_change_check_status:
                // 添加资产页面
                try {
                    showAddAssetDetailFragment();
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtil.toastShort("没有数据显示");
                }
                break;
            case R.id.txt_right_title:
                //判断是否自动同步数据
                try {
                    judgeIsSyncData();
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtil.toastShort("没有数据显示");
                }
                break;
            default:
                break;
        }
    }




    private void showAddAssetDetailFragment() {
        MainActivity activity = (MainActivity) getActivity();
        PromissionEntity pe = new PromissionEntity();
        pe.setFragment(new AddCheckDetailFragment());
        pe.setPosition(MainActivity.FRAGMENT_CUSTOM_ID);
        pe.setTitle("添加资产");
        Bundle bundle = new Bundle();
        bundle.putSerializable(Constants.CHECK_IN_DETAIL_NO, check.getId_());
        pe.setBundle(bundle);
        activity.onEventRegister(pe);
    }


}
